"""
简化版用户相关数据模型
"""

from tortoise import fields
from app.models.base.base import BaseModel


class User(BaseModel):
    """
    简化版统一用户模型
    """
    # 基础用户信息
    username = fields.CharField(max_length=50, unique=True, description="用户名")
    email = fields.CharField(max_length=255, unique=True, description="邮箱")
    password = fields.CharField(max_length=255, description="加密后的密码")
    
    # 用户显示信息
    nickname = fields.CharField(max_length=50, null=True, description="昵称")
    ## 加一个头像 。
    avatar = fields.CharField(max_length=255, null=True, description="头像URL")  
    # 添加这一行 - 反向关系
    roles: fields.ReverseRelation["Role"]  # 类型提示
    # roles = fields.ManyToManyField("models.Role", related_name="user_roles")

    # 状态控制
    is_active = fields.BooleanField(default=True, description="是否激活")
    is_superuser = fields.BooleanField(default=False, description="是否为超级用户")
    last_login = fields.DatetimeField(null=True, description="最后登录时间")
    
    class Meta:
        table = "users"
        table_description = "用户表"
        indexes = ["username", "email"]  # 明确定义索引
        
    def __str__(self):
        return f"User(id={self.id}, username={self.username})"
    
    async def update_last_login(self):
        """更新最后登录时间"""
        from datetime import datetime
        self.last_login = datetime.now()
        await self.save()


class Role(BaseModel):
    """
    用户角色关联模型
    一个用户可以在不同家庭中拥有不同角色
    """
    user = fields.ForeignKeyField('models.User', related_name='user_roles')
    family = fields.ForeignKeyField('models.Family', related_name='family_roles', null=True)  # null表示系统级角色
    
    # 角色类型：admin(管理员), member(成员), guest(访客)
    role_type = fields.CharField(max_length=20, description="角色类型")
    is_primary = fields.BooleanField(default=False, description="是否为主要角色")
    
    # 权限扩展
    permissions = fields.JSONField(default=list, description="额外权限")
    
    class Meta:
        table = "user_roles"
        table_description = "用户角色表"
        unique_together = (("user", "family"),)  # 每个用户在每个家庭中只有一个角色
        
    def __str__(self):
        family_info = f"family_{self.family_id}" if self.family_id else "system"
        return f"Role(user={self.user_id}, {family_info}, role={self.role_type})"


class UserFamily(BaseModel):
    """
    用户家庭关联模型
    记录用户所属的所有家庭
    """
    user = fields.ForeignKeyField('models.User', related_name='user_families')
    family = fields.ForeignKeyField('models.Family', related_name='family_users',null=True)
    
    # 在该家庭中的昵称
    family_nickname = fields.CharField(max_length=50, null=True, description="家庭内昵称")
    is_active = fields.BooleanField(default=True, description="是否在该家庭中激活")
    joined_at = fields.DatetimeField(auto_now_add=True, description="加入时间")
    
    class Meta:
        table = "user_families"
        table_description = "用户家庭关联表"
        unique_together = (("user", "family"),)
        
    def __str__(self):
        return f"UserFamily(user={self.user_id}, family={self.family_id})"


class UserLoginLog(BaseModel):
    """
    简化版用户登录日志
    """
    user = fields.ForeignKeyField('models.User', related_name='login_logs')
    login_time = fields.DatetimeField(auto_now_add=True, description="登录时间")
    ip_address = fields.CharField(max_length=45, null=True, description="登录IP")
    login_success = fields.BooleanField(default=True, description="登录是否成功")
    failure_reason = fields.CharField(max_length=100, null=True, description="失败原因")
    
    class Meta:
        table = "user_login_logs"
        table_description = "用户登录日志表"
        
    def __str__(self):
        return f"UserLoginLog(user={self.user_id}, time={self.login_time})"